<?php
class featured_media {
	var $CI;
	var $featured_media_model;
	public function __construct() {
		$this->CI = & get_instance ();
		$this->CI->load->model ( "website/featured_media_model" );
		$this->featured_media_model = $this->CI->featured_media_model;
	}
	public function query_featured_media_list($media_type) {
		return $this->featured_media_model->query_featured_media_list ( $media_type );
	}
	public function save_featured_media($featured_media) {
		$check_media_id_result = $this->check_media_id ( $featured_media ['media_id'], $featured_media ['media_type'] );
		if ($check_media_id_result ['result'] == false) {
			return $check_media_id_result;
		}
		$media_id_list = explode ( ",", $featured_media ['media_id'] );
		foreach ( $media_id_list as $id ) {
			if ($id != "") {
				$featured_media ['media_id'] = $id;
				$this->insert_featured_media ( $featured_media );
			}
		}
		
		$result ['result'] = true;
		$result ['message'] = "";
		$result ['redirect_url'] = base_url () . "index.php/website_featured_media/?media_type=" . $featured_media ['media_type'];
		return $result;
	}
	private function check_media_id($media_id, $media_type) {
		$result ['result'] = true;
		$result ['message'] = "";
		if ($media_id == "") {
			$result ['result'] = false;
			$result ['message'] = "媒体编号不能为空";
			return $result;
		}
		$this->CI->load->library ( "media/media" );
		$media_id_list = explode ( ",", $media_id );
		foreach ( $media_id_list as $id ) {
			if ($id != "") {
				$media_info = $this->CI->media->query_media ( $id );
				if ($media_info == null) {
					$result ['result'] = false;
					$result ['message'] = "编号为 " . $id . " 的媒体不存在";
					return $result;
				}
				if ($media_type != $media_info ['media_type']) {
					$result ['result'] = false;
					$result ['message'] = "编号为 " . $id . " 的媒体,与所选媒体类型不符";
					return $result;
				}
			}
		}
		return $result;
	}
	private function insert_featured_media($featured_media) {
		$this->featured_media_model->insert_featured_media ( $featured_media );
	}
	public function query_sort_num() {
		return intval ( $this->featured_media_model->query_sort_num () ) + 1;
	}
	public function query_featured_media_info($featured_id) {
		return $this->featured_media_model->query_featured_media_info ( $featured_id );
	}
	public function update_featured_media($featured_media, $featured_id) {
		$check_media_id_result = $this->check_media_id ( $featured_media ['media_id'], $featured_media ['media_type'] );
		if ($check_media_id_result ['result'] == false) {
			return $check_media_id_result;
		}
		$this->featured_media_model->update_featured_media ( $featured_media, $featured_id );
		$result ['result'] = true;
		$result ['message'] = "";
		$result ['redirect_url'] = base_url () . "index.php/website_featured_media/?media_type=" . $featured_media ['media_type'];
		return $result;
	}
	public function delete_featured_media($featured_id) {
		$this->featured_media_model->delete_featured_media ( $featured_id );
	}
}